import cacheUtils from "@/utils/CacheUtils";
import toast from "@/utils/Toast";
import qs from "qs";
import { userStore } from "@/stores/user";
import LoginService from "@/api/LoginService";
import CacheUtils from "@/utils/CacheUtils";

class RequestUtils {
  constructor(baseUrl = import.meta.env.VITE_APP_URL) {
    this.baseUrl = baseUrl;
  }

  static async _login() {
    const userInfoStore = userStore();
    cacheUtils.deleteCache("token");
    try {
      const res = await LoginService.WxCodeLogin();
      if (!res.newUser) {
        userInfoStore.userInfoInit(res);
      } else {
        CacheUtils.setCache("userInfo", res);
        userInfoStore.getCacheUserInfo();
      }
    } catch (err) {
      toast.info(err);
    }
  }

  static _responseInterceptor(response, resolve, reject, option) {
    if (response.statusCode !== 200) {
      switch (response.statusCode) {
        case 400:
          toast.info("请求参数错误！");
          break;
        case 404:
          toast.info("接口不存在！");
          break;
        case 500:
          toast.info("服务器错误！");
          break;
        default:
          toast.info("网络异常,请检查网络", { position: "bottom" });
          break;
      }
      reject(response);
      return;
    }
    if (response.data.error) {
      toast.info(response.data.message);
      if (response.data.code === 300) {
        RequestUtils._login();
        reject(response.data.message);
        return;
      }
      reject(response.data.message);
      return;
    }
    resolve(response.data.data);
  }

  request(option) {
    option = Object.assign(
      {
        method: "GET",
        header: {},
      },
      option
    );
    if (option.params) {
      option.url += `?${qs.stringify(option.params)}`;
    }
    let token = cacheUtils.getCache("token");
    if (token) {
      option.header.Token = token;
    }
    if (!option.data) {
      option.data = {};
    }
    option.header["X-Requested-With"] = "XMLHttpRequest";
    return new Promise((resolve, reject) => {
      uni.request({
        ...option,
        url: this.baseUrl + option.url,
        complete: (res) => {
          RequestUtils._responseInterceptor(res, resolve, reject, option);
        },
      });
    });
  }

  get(option) {
    return this.request({ ...option, method: "GET" });
  }

  post(option) {
    return this.request({ ...option, method: "POST" });
  }
}

export default new RequestUtils();
